package com.stylefeng.guns.wx.controller;

import com.stylefeng.guns.core.base.controller.BaseController;
import com.stylefeng.guns.core.base.tips.SuccessTip;
import com.stylefeng.guns.core.log.LogManager;
import com.stylefeng.guns.core.log.factory.LogTaskFactory;
import com.stylefeng.guns.core.shiro.ShiroDbRealm;
import com.stylefeng.guns.core.shiro.ShiroKit;
import com.stylefeng.guns.core.shiro.ShiroUser;
import com.stylefeng.guns.core.shiro.WxCodeAuthcToken;
import com.stylefeng.guns.core.util.SpringContextHolder;
import com.stylefeng.guns.modular.system.dao.UserMapper;
import com.stylefeng.guns.modular.system.model.User;
import com.stylefeng.guns.wx.exception.WxAuthException;
import me.chanjar.weixin.cp.api.WxCpService;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import static com.stylefeng.guns.core.support.HttpKit.getIp;

@RequestMapping("/oauth")
@Controller
public class OAuthController extends BaseController{

    @Autowired
    private UserMapper userMapper;

    @Autowired
    private WxCpService wxCpService;

    @RequestMapping(value = "")
    @ResponseBody
    public Object code(String code) {
        Subject currentUser = ShiroKit.getSubject();

        ShiroKit.clearCachedAuthorizationInfo();

        User user = null;
        try {
            String[] res = wxCpService.getOauth2Service().getUserInfo(code);
            user = userMapper.getByWxUserId(res[0]);
        } catch (Exception e) {
            throw new WxAuthException();
        }

        if (user == null) {
            throw new WxAuthException();
        }

        WxCodeAuthcToken token = new WxCodeAuthcToken(user.getId()+"");
        currentUser.login(token);


        ShiroUser shiroUser = ShiroKit.getUser();
        super.getSession().setAttribute("shiroUser", shiroUser);
        super.getSession().setAttribute("username", shiroUser.getAccount());

        LogManager.me().executeLog(LogTaskFactory.loginLog(shiroUser.getId(), getIp()));

        ShiroKit.getSession().setAttribute("sessionFlag", true);

        return new SuccessTip();
    }


}
